package videoCapture;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;

public class SoundAPI {

	private AudioFormat getFormat() {
		float sampleRate = 44100;  //44100
		int sampleSizeInBits = 16;
		int channels = 1;
		boolean signed = true;
		boolean bigEndian = true;
		return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,
				bigEndian);
	}

	public void Captrue() throws Exception {
		AudioFormat format = getFormat();
		DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
		final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
		line.open(format);
		line.start();

		int bufferSize = (int) format.getSampleRate() * format.getFrameSize();
		byte buffer[] = new byte[bufferSize];
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		int i = 0;
		while (true) {
			int count = line.read(buffer, 0, buffer.length);
			if (count > 0) {
				out.write(buffer, 0, count);
			}
			if (i++ > 10)
				break;
			System.out.println(i);
		}
		out.close();
		
		byte[] audioBytes = out.toByteArray();
		ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);
		AudioInputStream audioInputStream = new AudioInputStream(bais, format, audioBytes.length / format.getFrameSize());
		
		File file = new File("test");
//		audioInputStream = AudioSystem
//				.getAudioInputStream(file);
		audioInputStream.reset();
		AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, file);
		audioInputStream.close();
	}
	
	public static void main(String[] args) throws Exception {
		new SoundAPI().Captrue();
	}
}
